package handlers

import (
	"context"
	"math/rand"
	"ourplansystem/server/ent"
	"ourplansystem/server/ent/bottle"
	"ourplansystem/server/models"
	"strconv"
	"time"

	"github.com/gofiber/fiber/v2"
)

// BottleHandler 漂流瓶处理器
type BottleHandler struct {
	client *ent.Client
}

// NewBottleHandler 创建漂流瓶处理器
func NewBottleHandler(client *ent.Client) *BottleHandler {
	return &BottleHandler{client: client}
}

// CreateBottleRequest 创建漂流瓶请求
type CreateBottleRequest struct {
	Content   string   `json:"content"`
	Images    []string `json:"images"`
	CreatorID int64    `json:"creator_id"`
}

// UpdateBottleRequest 更新漂流瓶请求
type UpdateBottleRequest struct {
	Content string   `json:"content"`
	Images  []string `json:"images"`
}

// GetBottles 获取所有未删除的漂流瓶
func (h *BottleHandler) GetBottles(c *fiber.Ctx) error {
	ctx := context.Background()
	bottles, err := h.client.Bottle.Query().
		Where(bottle.DeletedAtIsNil()).
		WithCreator().
		All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取漂流瓶列表失败")
	}

	return models.Success(c, bottles)
}

// GetBottle 获取单个漂流瓶
func (h *BottleHandler) GetBottle(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的漂流瓶ID")
	}

	bottle, err := h.client.Bottle.Get(ctx, id)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "漂流瓶不存在")
		}
		return models.InternalServerError(c, "获取漂流瓶失败")
	}

	return models.Success(c, bottle)
}

// GetRandomBottle 随机获取一个漂流瓶
func (h *BottleHandler) GetRandomBottle(c *fiber.Ctx) error {
	ctx := context.Background()

	// 获取所有未删除的漂流瓶
	bottles, err := h.client.Bottle.Query().
		Where(bottle.DeletedAtIsNil()).
		WithCreator().
		All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取漂流瓶失败")
	}

	if len(bottles) == 0 {
		return models.NotFound(c, "还没有漂流瓶")
	}

	// 随机选择一个
	randomIndex := rand.Intn(len(bottles))
	randomBottle := bottles[randomIndex]

	return models.Success(c, randomBottle)
}

// CreateBottle 创建漂流瓶
func (h *BottleHandler) CreateBottle(c *fiber.Ctx) error {
	ctx := context.Background()
	var req CreateBottleRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	if req.Content == "" {
		return models.BadRequest(c, "内容不能为空")
	}

	if req.CreatorID == 0 {
		return models.BadRequest(c, "创建者ID不能为空")
	}

	builder := h.client.Bottle.
		Create().
		SetContent(req.Content).
		SetCreatorID(req.CreatorID)

	if len(req.Images) > 0 {
		builder.SetImages(req.Images)
	}

	bottle, err := builder.Save(ctx)
	if err != nil {
		return models.InternalServerError(c, "创建漂流瓶失败")
	}

	return models.SuccessWithMessage(c, "创建成功", bottle)
}

// UpdateBottle 更新漂流瓶
func (h *BottleHandler) UpdateBottle(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的漂流瓶ID")
	}

	var req UpdateBottleRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	builder := h.client.Bottle.UpdateOneID(id)

	if req.Content != "" {
		builder.SetContent(req.Content)
	}

	if len(req.Images) > 0 {
		builder.SetImages(req.Images)
	}

	bottle, err := builder.Save(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "漂流瓶不存在")
		}
		return models.InternalServerError(c, "更新漂流瓶失败")
	}

	return models.SuccessWithMessage(c, "更新成功", bottle)
}

// DeleteBottle 软删除漂流瓶
func (h *BottleHandler) DeleteBottle(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的漂流瓶ID")
	}

	// 软删除：设置 deleted_at 为当前时间
	now := time.Now()
	_, err = h.client.Bottle.UpdateOneID(id).
		SetDeletedAt(now).
		Save(ctx)

	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "漂流瓶不存在")
		}
		return models.InternalServerError(c, "删除漂流瓶失败")
	}

	return models.SuccessWithMessage(c, "删除成功", nil)
}

// GetDeletedBottles 获取所有已删除的漂流瓶（回收站）
func (h *BottleHandler) GetDeletedBottles(c *fiber.Ctx) error {
	ctx := context.Background()
	bottles, err := h.client.Bottle.Query().
		Where(bottle.DeletedAtNotNil()).
		WithCreator().
		All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取已删除漂流瓶失败")
	}

	return models.Success(c, bottles)
}

// RestoreBottle 恢复已删除的漂流瓶
func (h *BottleHandler) RestoreBottle(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的漂流瓶ID")
	}

	// 恢复：清空 deleted_at
	_, err = h.client.Bottle.UpdateOneID(id).
		ClearDeletedAt().
		Save(ctx)

	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "漂流瓶不存在")
		}
		return models.InternalServerError(c, "恢复漂流瓶失败")
	}

	return models.SuccessWithMessage(c, "恢复成功", nil)
}

// PermanentDeleteBottle 永久删除漂流瓶
func (h *BottleHandler) PermanentDeleteBottle(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的漂流瓶ID")
	}

	err = h.client.Bottle.DeleteOneID(id).Exec(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "漂流瓶不存在")
		}
		return models.InternalServerError(c, "永久删除漂流瓶失败")
	}

	return models.SuccessWithMessage(c, "永久删除成功", nil)
}
